import axios from 'axios'
import Vue from 'vue'
import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const http = axios.create({
  baseURL: '/',
  timeout: 10000
})

http.interceptors.request.use(function (config) {
  if (sessionStorage.token) {
    nprogress.start()
    config.headers.Authorization = 'Bearer ' + sessionStorage.token
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

http.interceptors.response.use(res => {
  nprogress.done()
  return res
}, err => {
  const { message } = err
  if (message.includes('timeout')) {
    Vue.prototype.$message.error('请求超时')
  }
  if (err.response.status === 404) {
    Vue.prototype.$message.error('后端接口出错')
  }
  if (err.response.data.message) {
    Vue.prototype.$message.error(err.response.data.message)
    if (err.response.status === 401) {
      router.push('/login')
    }
  }
  return Promise.reject(err)
})

export default http
